<template>
  <div class="order-print">
    <div class="middle">
      <!-- 今日/昨日/近7日/近30日等，创建订单按钮，关键词搜索 -->

      <div class="center-search-wrap">
        <div>
          <SearchForm
            ref="searchFormRef"
            :list="[...formList]"
            @submit="search"
            @reset="reset"
            @daterangeChange="daterangeChange"
          ></SearchForm>
        </div>
      </div>
    </div>

    <!-- 表单数据 -->
    <el-table class="jzt-table" :data="list" stripe style="width: 100%">
      <el-table-column prop="purchaseOrderNo" show-overflow-tooltip label="采购编码" width="180" />
      <el-table-column prop="orderTime" show-overflow-tooltip label="下单时间" width="140" />
      <el-table-column prop="name" show-overflow-tooltip label="商品种类信息" width="140">
        <template #default="scope">
          <span>{{ scope.row.categoryNum || 0 }}种商品/({{ scope.row.detailNum || 0 }}件)</span>
        </template>
      </el-table-column>
      <el-table-column prop="factoryState" show-overflow-tooltip label="状态" width="120">
        <template #default="scope">
          <el-tag type="primary" v-show="scope.row.factoryState === 5">部分发货</el-tag>
          <el-tag type="success" v-show="scope.row.factoryState === 6">已发货</el-tag>
          <el-tag type="warning" v-show="scope.row.factoryState === 4">待发货</el-tag>
          <el-tag type="warning" v-show="scope.row.factoryState === 2">待接单</el-tag>
          <el-tag type="danger" v-show="scope.row.factoryState === 3">已拒绝</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="goodsNum" show-overflow-tooltip label="数量" />
      <el-table-column prop="detailNum" show-overflow-tooltip label="件数" />
      <el-table-column prop="sendedNum" show-overflow-tooltip label="实际发货数量" />
      <el-table-column prop="sendedPartNum" show-overflow-tooltip label="实际发货件数" />
      <el-table-column prop="receivingName" show-overflow-tooltip label="收件人" width="120" />
      <el-table-column prop="receivingMobile" show-overflow-tooltip label="收件人手机" width="120" />
      <el-table-column prop="receivingAddress" show-overflow-tooltip label="收货地址" width="200">
        <template #default="scope">
          <span>{{ scope.row.receivingAreaDetail ? scope.row.receivingAreaDetail + scope.row.receivingAddress : "-" }}</span>
        </template>
      </el-table-column>

      <el-table-column fixed="right" prop="action" label="操作" width="240">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="toPathDetail(scope.row)"> 查看 </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="
              toPath({
                path: '/order/procure/list',
                query: { purchaseOrderId: scope.row.purchaseOrderId, redirect: `/order/print` }
              })
            "
          >
            清单
          </el-button>
          <el-button
            v-if="scope.row.factoryState === 4 || scope.row.factoryState === 5"
            link
            type="primary"
            size="small"
            @click="
              toPath({
                path: '/order/procure/send',
                query: { purchaseOrderId: scope.row.purchaseOrderId, redirect: `/order/print` }
              })
            "
          >
            发货
          </el-button>
          <div
            v-show="scope.row.factoryState === 5 || scope.row.factoryState === 6 || scope.row.process === 4"
            class="ml12"
            style="display: inline-block"
          >
            <el-popover placement="bottom-end" popper-class="action-more" teleported :width="100" trigger="hover">
              <template #reference>
                <el-button link type="primary" size="small">更多</el-button>
              </template>
              <div class="action-btn">
                <p>
                  <el-button
                    v-show="scope.row.factoryState === 5 || scope.row.factoryState === 6 || scope.row.process === 4"
                    link
                    type="primary"
                    size="small"
                    style="width: 100%; justify-content: flex-start"
                    @click="toPathDetail(scope.row)"
                  >
                    修改物流
                  </el-button>
                </p>
              </div>
            </el-popover>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pt20 pb20" style="display: flex; justify-content: flex-end">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="pagination.sizes"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 拒绝订单弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="'拒绝订单'"
      width="500"
      align-center
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="handleClose"
    >
      <div class="form-wrap">
        <el-form :model="form" ref="formRef" label-width="auto" style="max-width: 600px">
          <el-form-item
            prop="refuseType"
            label="取消原因"
            :rules="{ required: true, message: '请选择', trigger: ['blur', 'change'] }"
          >
            <el-select v-model="form.refuseType" placeholder="请选择" clearable>
              <el-option v-for="item in causeList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="refuseRemarks" label="备注">
            <el-input
              :rows="2"
              type="textarea"
              placeholder="请输入"
              v-model="form.refuseRemarks"
              oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="refuseOrderSubmit">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 确认删除 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenDel"
      :message="'删除后，当前采购单将被永久删除，请谨慎操作，是否继续删除？'"
      :submitBtnText="'确认'"
      @submit="returnSubmitDel"
    />
    <!-- 确认接单 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenReceive"
      :type="'info'"
      :title="'接单提醒'"
      :message="'您正在操作接单，接单前请详细核查订单消息，是否继续执行接单？'"
      :submitBtnText="'确认接单'"
      @submit="returnSubmitReceive"
    />
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from "vue";
import SearchForm from "@/components/SearchForm";
import { Search, RefreshRight } from "@element-plus/icons-vue";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";
import { getProcureList, delOrder, acceptOrder, refuseOrder, printList } from "@/apis/order/procure";
import moment from "moment";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();

const options = ref([
  { label: "全部", value: 0 },
  { label: "采购编码", value: 1 },
  { label: "姓名", value: 2 },
  { label: "手机号", value: 3 }
]);
const formList = ref([
  {
    label: "发货状态",
    model: "factoryState",
    type: "select",
    labelWidth: "90",
    data: [
      { label: "待发货", value: 4 },
      { label: "部分发货", value: 5 },
      { label: "已发货(全部)", value: 6 }
    ]
  },
  {
    label: "订单搜索",
    model: "ddKey-ddKeyword",
    type: "select-input",
    labelWidth: "90",
    data: [
      {
        value: "1",
        label: "全部"
      },
      {
        value: "2",
        label: "收货姓名"
      },
      {
        value: "3",
        label: "收货电话"
      },
      {
        value: "4",
        label: "采购编码"
      }
    ]
  }
]);
const searchFormRef = ref();
const formData = ref({});
const postData = ref({ date: null });
const list = ref([]);
const pagination = ref({
  page: 1,
  size: 10,
  sizes: [10, 20, 30, 40, 50],
  total: 0
});
const optionInfo = ref({ isShow: false });
const activeName = ref("1");
const dialogVisible = ref(false); //拒绝订单-弹窗
const form = ref({}); //拒绝订单表单
const formRef = ref();
const causeList = ref([
  { label: "原材料上涨", value: 1 },
  { label: "商品停产", value: 2 },
  { label: "缺货无法交易", value: 3 },
  { label: "其他原因", value: 4 }
]); //取消原因 下拉数据
const _isOpenDel = ref(false);
const _isOpenReceive = ref(false);
const currObj = ref({}); //当前点击的行 订单对象

onMounted(() => {
  getList();
});

const toPath = obj => {
  //打开新页签
  const routeUrl = router.resolve(obj);
  window.open(routeUrl.href, "_blank");
};

/**
 * 跳转到详情页-打开一页新的页签
 */
const toPathDetail = row => {
  const baseRouter = window.microApp.router.getBaseAppRouter();
  const routeUrl = baseRouter.resolve({
    path: "/factory/order/procure/detail",
    query: { purchaseOrderId: row.purchaseOrderId, redirect: "/order/procure", tabs: activeName.value }
  });
  window.open(routeUrl.href, "_blank");
};

const changeDate = val => {
  const { start, end } = getTimeRange(val);
  getList();
};

const daterangeChange = () => {
  postData.value = { date: null };
};

// 打开拒绝订单弹窗
const handleOpenReject = () => {
  dialogVisible.value = true;
  nextTick(() => {
    formRef.value.resetFields();
  });
};
//关闭拒绝订单弹窗
const handleClose = () => {
  dialogVisible.value = false;
};

//确认拒绝订单
const refuseOrderSubmit = () => {
  refuseOrder({
    purchaseOrderId: currObj.value.purchaseOrderId,
    ...form.value
  }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "拒绝订单成功",
        type: "success"
      });
      getList();
      handleClose();
    }
  });
};

//删除弹窗打开
const clickDel = () => {
  _isOpenDel.value = true;
};
//确认删除
const returnSubmitDel = () => {
  delOrder({ purchaseOrderId: currObj.value.purchaseOrderId }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
      _isOpenDel.value = false;
    }
  });
};

//接单弹窗打开
const clickReceive = () => {
  _isOpenReceive.value = true;
};
//确认接单
const returnSubmitReceive = () => {
  acceptOrder({ purchaseOrderId: currObj.value.purchaseOrderId }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "接单成功",
        type: "success"
      });
      getList();
      _isOpenReceive.value = false;
    }
  });
};

//查询入库单列表数据
const getList = () => {
  // console.log(11111, getTimeRange(postData.value.date));
  printList({
    ...formData.value,
    page: pagination.value.page,
    size: pagination.value.size
  }).then(res => {
    if (res.code === 200) {
      list.value = res.data.records;
      pagination.value.total = res.data.total;
    }
  });
};

const getTimeRange = num => {
  if (num !== null) {
    let start = "";
    let end = "";
    if (num === 0) {
      start = moment().startOf("day").format("YYYY/MM/DD HH:mm:ss"); // 带有时分秒
      end = moment().endOf("day").format("YYYY/MM/DD HH:mm:ss"); // 带有时分秒
    } else if (num === 1) {
      start = moment().subtract(1, "day").startOf("day").format("YYYY/MM/DD HH:mm:ss"); // 带有时分秒
      end = moment().subtract(1, "day").endOf("day").format("YYYY/MM/DD HH:mm:ss"); // 带有时分秒
    } else {
      start = moment()
        .subtract(num - 1, "day")
        .startOf("day")
        .format("YYYY/MM/DD HH:mm:ss"); // 带有时分秒
      end = moment().format("YYYY/MM/DD HH:mm:ss"); // 带有时分秒
    }

    searchFormRef.value.setFormData("orderTime", [start, end]);
    return { start, end };
  }
};

// 表单查询组件submit回调
const search = form => {
  // console.log("查询表单数据===", form);
  if (form) {
    let _form = JSON.parse(JSON.stringify(form));
    if (_form.ddKey === "1") {
      // 全部
      _form.orderKeyword = _form.ddKeyword;
    } else if (_form.ddKey === "2") {
      //收货姓名
      _form.receivingName = _form.ddKeyword;
    } else if (_form.ddKey === "3") {
      //收货电话
      _form.receivingMobile = _form.ddKeyword;
    } else if (_form.ddKey === "4") {
      //采购编码
      _form.purchaseOrderNo = _form.ddKeyword;
    }
    delete _form?.orderTime;
    delete _form?.khKey;
    delete _form?.ddKey;
    delete _form?.ddKeyword;
    formData.value = _form;
  } else {
    formData.value = {};
  }
  nextTick(() => {
    getList();
  });
};
//清空查询表单
const reset = () => {
  search("");
  daterangeChange();
};

const handleSizeChange = val => {
  pagination.value.size = val;
  getList();
};
const handleCurrentChange = val => {
  pagination.value.page = val;
  getList();
};
</script>

<style lang="scss">
.action-more {
  z-index: 2 !important;
  min-width: 0 !important;
}
</style>
<style lang="scss" scoped>
.order-print {
  height: calc(100% - 20px);
  overflow-y: auto;
  padding: 0 20px 20px 20px;

  .search-wrap {
    padding: 20px;
    overflow-x: hidden;
    background-color: #f6f8fa;
  }

  .middle {
    position: sticky;
    top: 0;
    background-color: white;
    z-index: 22;
    :deep(.el-tabs__header.is-top) {
      margin-bottom: 0;
    }
  }
  .center-search-wrap {
    :deep(.el-input-group__append) {
      padding: 0;
    }
    :deep(.el-select) {
      .el-select__wrapper {
        background-color: #f2f3f5 !important;
      }
    }
    :deep(.jzt-select-input.el-input) {
      .el-select__wrapper {
        background-color: white !important;
      }
    }

    // .el-select {
    //   .el-select__wrapper {
    //     background-color: red !important;
    //   }
    // }
    & > div {
      display: flex;
      justify-content: space-between;
      padding: 20px 0;
    }
    :deep(.el-form) {
      flex: 1;
    }
    .btn-wrap {
      width: 80px;
    }
  }
}
</style>
